package com.slipper.codeless.controller;

import com.google.gson.reflect.TypeToken;
import com.slipper.codeless.resolve.SqlBuilderFactory;
import com.slipper.codeless.resolve.query.QueryResolver;
import com.slipper.codeless.service.CodelessService;
import com.slipper.common.bo.UserDetail;
import com.slipper.common.service.CommonService;
import com.slipper.constants.Constants;
import com.slipper.core.cache.CacheKey;
import com.slipper.core.cache.CacheUtil;
import com.slipper.core.tree.Node;
import com.slipper.core.tree.Tree;
import com.slipper.core.tree.TreeInfo;
import com.slipper.core.tree.TreeUtil;
import com.slipper.exception.CommonException;
import com.slipper.exception.NotLoginException;
import com.slipper.system.codeless.bo.DataModelBO;
import com.slipper.system.codeless.bo.PageBO;
import com.slipper.system.codeless.bo.PageCompBO;
import com.slipper.system.codeless.service.*;
import com.slipper.system.dictionary.bo.DictionaryDataBO;
import com.slipper.system.dictionary.service.DictionaryDataService;
import com.slipper.system.employee.bo.EmployeeBO;
import com.slipper.system.employee.service.EmployeeService;
import com.slipper.system.menu.bo.MenuBO;
import com.slipper.system.menu.service.MenuService;
import com.slipper.system.message.bo.MessageBO;
import com.slipper.system.message.service.MessageService;
import com.slipper.system.message.service.MessageStatusService;
import com.slipper.system.organization.bo.OrganizationBO;
import com.slipper.system.organization.service.OrganizationService;
import com.slipper.system.role.bo.RoleBO;
import com.slipper.system.role.bo.RolePrivilegeBO;
import com.slipper.system.role.service.RoleService;
import com.slipper.system.setting.bo.SettingBO;
import com.slipper.system.setting.service.SettingService;
import com.slipper.system.subsystem.bo.SubsystemBO;
import com.slipper.system.subsystem.service.SubsystemService;
import com.slipper.util.BeanUtil;
import com.slipper.util.DateUtil;
import com.slipper.util.ResultUtil;
import com.slipper.util.Tool;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/business")
public class BusinessController {
    @Resource
    private CodelessService codelessService;
    @Resource
    private PageService pageService;
    @Resource
    private PageCompService pageCompService;
    @Resource
    private PageButtonService pageButtonService;
    @Resource
    private DataTableService dataTableService;
    @Resource
    private DataFormService dataFormService;
    @Resource
    private DataFieldService dataFieldService;
    @Resource
    private MenuService menuService;
    @Resource
    private RoleService roleService;
    @Resource
    private EmployeeService employeeService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private SubsystemService subsystemService;
    @Resource
    private SettingService settingService;
    @Resource
    private DataFieldRelevanceService dataFieldRelevanceService;
    @Resource
    private DataModelService dataModelService;
    @Resource
    public QueryResolver queryResolver;
    @Resource
    private CommonService commonService;
    @Resource
    private DictionaryDataService dictionaryDataService;
    @Resource
    private MessageService messageService;
    @Resource
    private MessageStatusService messageStatusService;

    @PostMapping("/user")
    public String user() {
        UserDetail userDetail = Constants.getCurrentUser();
        Map<String, Object> result = new HashMap<>();
        result.put("token", Tool.getUUID());
        result.put("user", userDetail.getEmployee());
        result.put("userData", userDetail.getUser());
        result.put("orgData", userDetail.getOrg());
        result.put("dateData", DateUtil.currDate());
        return ResultUtil.successResult(result);
    }

    @PostMapping("/page/{id}")
    public String queryPageById(@PathVariable("id") String id) {
        return queryPageById(null, id);
    }

    @PostMapping("/page/{menuId}/{id}")
    public String queryPageById(@PathVariable("menuId") String menuId, @PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }

        UserDetail user = Constants.getCurrentUser(false);
        if (Tool.isNotBlank(menuId)) {
            codelessService.checkPermit(user, menuId);
        } else {
            codelessService.checkPermit(user, id);
        }

        PageBO page = pageService.queryBy(id);

        if (Tool.isBlank(menuId)) {
            if (user != null && !page.getCompList().isEmpty() && !user.isSuperAdmin()) {
                List<RolePrivilegeBO> privilegeList = user.getPrivilegeList();
                if (!privilegeList.isEmpty()) {
                    page.setCompList(page.getCompList().stream()
                            .filter(comp -> privilegeList.stream()
                                    .anyMatch(privilege -> privilege.getPrivilegeId().equals(comp.getId())))
                            .collect(Collectors.toList()));
                } else {
                    page.setCompList(Collections.emptyList());
                }
            }
        }

        return ResultUtil.successResult(page);
    }

    @PostMapping("/page-comp/{id}")
    public String queryPageCompById(@PathVariable("id") String id) {
        return queryPageCompById(null, id);
    }

    @PostMapping("/page-comp/{menuId}/{id}")
    public String queryPageCompById(@PathVariable("menuId") String menuId, @PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }

        UserDetail user = Constants.getCurrentUser(false);
        if (Tool.isNotBlank(menuId)) {
            codelessService.checkPermit(user, menuId);
        } else {
            codelessService.checkPermit(user, id);
        }

        PageCompBO pageComp = pageCompService.queryBy(id);

        if (Tool.isBlank(menuId)) {
            if (user != null && !pageComp.getButtonList().isEmpty() && !user.isSuperAdmin()) {
                List<RolePrivilegeBO> privilegeList = user.getPrivilegeList();
                if (!privilegeList.isEmpty()) {
                    pageComp.setButtonList(pageComp.getButtonList().stream()
                            .filter(button -> privilegeList.stream()
                                    .anyMatch(privilege -> privilege.getPrivilegeId().equals(button.getId())))
                            .collect(Collectors.toList()));
                } else {
                    pageComp.setButtonList(Collections.emptyList());
                }
            }
        }

        return ResultUtil.successResult(pageComp);
    }

    @PostMapping(value = "/page-button/list")
    public String queryPageButtonList() {
        return ResultUtil.successResult(pageButtonService.queryAll());
    }

    @PostMapping(value = "/data-table/{id}")
    public String queryDataTableById(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(dataTableService.queryBy(id));
    }

    @PostMapping(value = "/data-form/{id}")
    public String queryDataFormById(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(dataFormService.queryBy(id));
    }

    @PostMapping(value = "/data-field/{id}")
    public String queryDataFieldById(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(dataFieldService.queryBy(id));
    }

    @PostMapping(value = "/data-field/{id}/tree")
    public String queryTreeByDataFieldId(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }

        List<Tree> treeList = new ArrayList<>();
        dataFieldRelevanceService.queryFieldId(id).forEach(relevance -> {
            TreeInfo treeInfo = new TreeInfo("");
            treeInfo.setRootId(Constants.ROOT_ID);
            treeInfo.setIdField(relevance.getNodeFieldName());
            treeInfo.setPidField(relevance.getParentFieldName());
            treeInfo.setTextField(relevance.getShowFieldName());
            treeInfo.setSortField(relevance.getOrdinalFieldName() + "_ordinal");
            treeInfo.setNodeType(relevance.getId());

            DataModelBO dataModel = dataModelService.queryBy(relevance.getDataModelId());
            if (dataModel == null) throw new CommonException("数据模型信息不存在！");
            dataModel.setFieldList(dataFieldService.queryListBy(dataModel.getId()));

            Map<String, Object> queryMap = SqlBuilderFactory.buildQueryMap(
                    queryResolver.resolve(dataModel, new HashMap<>()));

            List<Map<String, Object>> dataList = commonService.queryList(queryMap);
            if (Tool.isNotBlank(relevance.getOrdinalFieldName())) {
                dataList.sort((o1, o2) -> {
                    if (o1 == null && o2 == null) return 0;

                    if (o1 == null || o1.get(relevance.getOrdinalFieldName()) == null) {
                        return -1;
                    }
                    if (o2 == null || o2.get(relevance.getOrdinalFieldName()) == null) {
                        return 1;
                    }
                    return o1.get(relevance.getOrdinalFieldName()).toString()
                            .compareTo(o2.get(relevance.getOrdinalFieldName()).toString());
                });
                int i = 0;
                for (Map<String, Object> data : dataList) {
                    data.put(relevance.getOrdinalFieldName() + "_ordinal", ++i);
                }
            }
            treeList.add(new Tree(treeInfo, dataList));
        });

        return ResultUtil.successResult(TreeUtil.buildTree("asc", treeList.toArray(new Tree[]{})));
    }

    @PostMapping(value = "/data-field/list/{modelId}")
    public String queryDataFieldList(@PathVariable("modelId") String modelId) {
        return ResultUtil.successResult(dataFieldService.queryListBy(modelId));
    }

    @PostMapping("/menu/tree/{subsystemId}")
    public String queryMenuTree(@PathVariable("subsystemId") String subsystemId) {
        UserDetail userDetail = Constants.getCurrentUser();
        if (userDetail == null) {
            throw new NotLoginException();
        }

        if (Tool.isBlank(subsystemId)) {
            return ResultUtil.failureResult("500", "请先选择子系统！");
        }

        MenuBO menuQO = new MenuBO();
        menuQO.setSubsystemId(subsystemId);
        menuQO.setEmployeeId(userDetail.getEmployeeId());
        List<MenuBO> menuList = this.menuService.queryUserMenus(menuQO);

        TreeInfo treeInfo = new TreeInfo("菜单树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("name");
        treeInfo.setHrefField("vuePath");
        treeInfo.setSortField("ordinal");
        return ResultUtil.successResult(TreeUtil.buildTree(treeInfo, menuList));
    }

    @PostMapping("/organization/change/{id}")
    public String changeOrganization(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("切换部门参数不正确！");
        }

        UserDetail userDetail = Constants.getCurrentUser();
        EmployeeBO employee = userDetail.getEmployee();

        List<OrganizationBO> list = employee.getOrganizationList().stream()
                .filter(organizationBO -> organizationBO.getId().equals(id))
                .toList();
        if (list.isEmpty()) {
            return ResultUtil.failureResult("无此部门权限，切换失败！");
        }

        employee.setOrganizationId(id);
        employeeService.updateOrganization(employee);

        OrganizationBO unit = organizationService.queryUnit(id);
        userDetail.setUnitId(unit == null ? null : unit.getId());
        userDetail.setOrganization(list.getFirst());
        employee.setUnitId(userDetail.getUnitId());
        employee.setOrgId(userDetail.getOrgId());
        employee.setOrgName(userDetail.getOrgName());

        Constants.setSessionUser(userDetail);
        return ResultUtil.successResult(employee);
    }

    @PostMapping(value = "/subsystem/{id}")
    public String querySubsystemById(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(subsystemService.queryBy(id));
    }

    @PostMapping(value = "/visual-comp/{id}")
    public String queryVisualCompById(@PathVariable("id") String id) {
        if(Tool.isBlank(id)) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(dataTableService.queryBy(id));
    }

    @PostMapping("/subsystem/list")
    public String querySubsystemList() {
        UserDetail userDetail = Constants.getCurrentUser();

        SubsystemBO subsystemQO = new SubsystemBO();
        subsystemQO.setValid(Constants.YES);
        if (!userDetail.isSuperAdmin()) {
            subsystemQO.setType(Constants.Subsystem.TYPE_SUBSYSTEM);
        }
        List<SubsystemBO> subsystemList = subsystemService.queryList(subsystemQO);
        if (!subsystemList.isEmpty() && !userDetail.isSuperAdmin()) {
            List<RolePrivilegeBO> privilegeList = userDetail.getPrivilegeList();
            if (!privilegeList.isEmpty()) {
                subsystemList = subsystemList.stream()
                        .filter(subsystem -> privilegeList.stream()
                                .anyMatch(privilege -> privilege.getPrivilegeId().equals(subsystem.getId())))
                        .collect(Collectors.toList());
            } else {
                subsystemList = Collections.emptyList();
            }
        }
        return ResultUtil.successResult(subsystemList);
    }

    @PostMapping("/role/list")
    public String queryRoleList() {
        RoleBO roleQO = new RoleBO();
        roleQO.setAdmin(Constants.NO);
        if (!Constants.getCurrentUser().isSuperAdmin()) {
            roleQO.setEmployeeId(Constants.getCurrentUserId());
        }
        return ResultUtil.successResult(roleService.queryList(roleQO));
    }

    @PostMapping("/region/tree")
    public String queryRegionTree() {
        List<OrganizationBO> organizationList;
        OrganizationBO bo = new OrganizationBO();
        bo.setValid(Constants.VALID);
        organizationList = organizationService.queryList(bo)
                .stream()
                .filter(item -> OrganizationBO.TYPE_AREA.equals(item.getType()))
                .toList();

        TreeInfo treeInfo = new TreeInfo("区划树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("name");
        treeInfo.setSortField("ordinal");
        return ResultUtil.successResult(TreeUtil.buildTree(treeInfo, organizationList, "asc"));
    }

    @PostMapping("/unit/tree")
    public String queryUnitTree() {
        List<OrganizationBO> organizationList;
        UserDetail userDetail = Constants.getCurrentUser();
        if (userDetail.isSuperAdmin()) {
            OrganizationBO bo = new OrganizationBO();
            bo.setValid(Constants.VALID);
            organizationList = organizationService.queryList(bo)
                    .stream()
                    .filter(item -> OrganizationBO.TYPE_AREA.equals(item.getType()) || OrganizationBO.TYPE_UNIT.equals(item.getType()))
                    .toList();
        } else {
            organizationList = new ArrayList<>();
            organizationList.add(organizationService.queryBy(userDetail.getUnitId()));
        }

        TreeInfo treeInfo = new TreeInfo("单位树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("name");
        treeInfo.setSortField("ordinal");
        return ResultUtil.successResult(TreeUtil.buildTree(treeInfo, organizationList, "asc"));
    }

    @PostMapping("/ent/tree")
    public String queryEntTree() {
        List<OrganizationBO> organizationList;
        UserDetail userDetail = Constants.getCurrentUser();
        if (userDetail.isSuperAdmin()) {
            OrganizationBO bo = new OrganizationBO();
            bo.setValid(Constants.VALID);
            organizationList = organizationService.queryList(bo)
                    .stream()
                    .filter(item -> OrganizationBO.TYPE_AREA.equals(item.getType()) || OrganizationBO.TYPE_ENT.equals(item.getType()))
                    .toList();
        } else {
            organizationList = new ArrayList<>();
            organizationList.add(organizationService.queryBy(userDetail.getUnitId()));
        }

        TreeInfo treeInfo = new TreeInfo("企业树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("name");
        treeInfo.setSortField("ordinal");
        return ResultUtil.successResult(TreeUtil.buildTree(treeInfo, organizationList, "asc"));
    }

    @PostMapping("/organization/id-name")
    public String queryOrganizationName(@RequestBody OrganizationBO bo) {
        if (bo.getIds() == null || bo.getIds().length == 0) return "";
        List<OrganizationBO> organizationList = organizationService.queryList(bo);
        return ResultUtil.successResult(null, organizationList.stream().map(OrganizationBO::getName).collect(Collectors.joining(",")));
    }

    @PostMapping("/organization/tree")
    public String queryOrganizationTree() {
        List<OrganizationBO> organizationList;
        UserDetail userDetail = Constants.getCurrentUser();
        if (userDetail.isSuperAdmin()) {
            OrganizationBO bo = new OrganizationBO();
            bo.setValid(Constants.VALID);
            organizationList = organizationService.queryList(bo);
        } else {
            organizationList = organizationService.queryRelation(userDetail.getOrgId());
        }

        TreeInfo treeInfo = new TreeInfo("部门树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("name");
        treeInfo.setSortField("ordinal");
        return ResultUtil.successResult(TreeUtil.buildTree(treeInfo, organizationList, "asc"));
    }

    @PostMapping("/employee/id-name")
    public String queryEmployeeName(@RequestBody EmployeeBO bo) {
        if (bo.getIds() == null || bo.getIds().length == 0) return "";

        String[] ids = Arrays.stream(bo.getIds()).map(id -> id.split("@")[1]).toArray(String[]::new);
        bo.setIds(ids);
        List<EmployeeBO> employeeList = employeeService.queryByIds(bo);
        return ResultUtil.successResult(null, employeeList.stream().map(EmployeeBO::getName).collect(Collectors.joining(",")));
    }

    @PostMapping("/employee/tree")
    public String queryEmployeeTree() {
        List<OrganizationBO> organizationList;
        UserDetail userDetail = Constants.getCurrentUser();
        if (userDetail.isSuperAdmin()) {
            OrganizationBO bo = new OrganizationBO();
            bo.setValid(Constants.VALID);
            organizationList = organizationService.queryList(bo);
        } else {
            organizationList = organizationService.queryRelation(userDetail.getOrgId());
            organizationList.stream()
                    .filter(org -> org.getId().equals(userDetail.getUnitId()))
                    .findFirst()
                    .ifPresent(org -> org.setParentId(Constants.ROOT_ID));
        }

        EmployeeBO employeeQO = new EmployeeBO();
        if (!userDetail.isSuperAdmin()) {
            String[] orgIds = organizationList.stream().map(OrganizationBO::getId).toArray(String[]::new);
            employeeQO.setOrganizationIds(orgIds);
        }
        employeeQO.setValid(Constants.VALID);
        employeeQO.setSortField("e.ordinal asc, e.name asc");
        List<EmployeeBO> employeeList = this.employeeService.queryListWithOrg(employeeQO);
        employeeList.forEach(employee -> employee.setType("10"));
        BeanUtil.setOrdinal(employeeList);

        TreeInfo organizationTreeInfo = new TreeInfo("人员树");
        organizationTreeInfo.setRootId(Constants.ROOT_ID);
        organizationTreeInfo.setIdField("id");
        organizationTreeInfo.setPidField("parentId");
        organizationTreeInfo.setTextField("name");

        TreeInfo employeeTreeInfo = new TreeInfo("人员树");
        employeeTreeInfo.setConcatIdWithPid(true);
        employeeTreeInfo.setIdField("id");
        employeeTreeInfo.setPidField("organizationId");
        employeeTreeInfo.setTextField("name");

        Node rootNode = TreeUtil.buildTree("asc",
                new Tree(organizationTreeInfo, organizationList),
                new Tree(employeeTreeInfo, employeeList));
        return ResultUtil.successResult(rootNode);
    }

    @PostMapping("/dictionary/all-dict-data")
    public String queryAllDicData() {
        Type type = new TypeToken<Map<String, List<Map<String, String>>>>(){}.getType();
        Map<String, List<Map<String, String>>> resultMap = CacheUtil.get(CacheKey.Dictionary.KEY, type);
        if (resultMap == null) {
            List<DictionaryDataBO> list = this.dictionaryDataService.queryList(new DictionaryDataBO());
            Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
            list.forEach(bo -> {
                List<Map<String, String>> result = finalMap.computeIfAbsent(bo.getDictId(), k -> new LinkedList<>());
                Map<String, String> data = new HashMap<>();
                data.put("pid", bo.getDictParent());
                data.put("key", bo.getDictKey());
                data.put("value", bo.getDictValue());
                data.put("color", bo.getColor());
                data.put("ordinal", String.valueOf(bo.getOrdinal()));
                result.add(data);
            });
            resultMap = finalMap;
            CacheUtil.set(CacheKey.Dictionary.KEY, resultMap, 60 * 60);
        }
        return ResultUtil.successResult(resultMap);
    }

    @PostMapping("/menu/portal-tree")
    public String queryPortalMenuTree() {
        SubsystemBO subsystemBO = new SubsystemBO();
        subsystemBO.setType(Constants.Subsystem.TYPE_PORTAL);
        subsystemBO.setValid(Constants.YES);
        List<SubsystemBO> subsystemList = subsystemService.queryList(subsystemBO);
        if (subsystemList.isEmpty()) return ResultUtil.failureResult("500", "门户端未启用！");

        MenuBO menuQO = new MenuBO();
        menuQO.setSubsystemId(subsystemList.getFirst().getId());
        List<MenuBO> menuList = this.menuService.queryList(menuQO);

        TreeInfo treeInfo = new TreeInfo("菜单树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("name");
        treeInfo.setHrefField("vuePath");
        treeInfo.setSortField("ordinal");
        return ResultUtil.successResult(TreeUtil.buildTree(treeInfo, menuList));
    }

    @PostMapping("/password/update")
    public String updatePassword(@RequestBody EmployeeBO bo) {
        if (Tool.isBlank(bo.getPassword())) {
            return ResultUtil.failureResult("密码不能为空！");
        }

        SettingBO setting = settingService.querySetting();
        if (Constants.YES.equals(setting.getPasswordCheck())) {
            String upper = "(?=.*[A-Z]).+$";
            String lower = "(?=.*[a-z]).+$";
            String digit = "(?=.*[0-9]).+$";
            String special = "(?=.*[`~!@#$%^&*()_+{}|<>/;:'\"]).+$";
            if (Constants.YES.equals(setting.getPasswordUpperLetter()) && !bo.getPassword().matches(upper)) {
                return ResultUtil.failureResult("密码必须包含有大写字母！");
            } else if (Constants.YES.equals(setting.getPasswordLowerLetter()) && !bo.getPassword().matches(lower)) {
                return ResultUtil.failureResult("密码必须包含有小写字母！");
            } else if (Constants.YES.equals(setting.getPasswordDigit()) && !bo.getPassword().matches(digit)) {
                return ResultUtil.failureResult("密码必须包含有数字！");
            } else if (Constants.YES.equals(setting.getPasswordSpecialChar()) && !bo.getPassword().matches(special)) {
                return ResultUtil.failureResult("密码必须包含有特殊字符！");
            } else if (setting.getPasswordMinLen() != null
                    && setting.getPasswordMinLen() > 0
                    && bo.getPassword().length() < setting.getPasswordMinLen()) {
                return ResultUtil.failureResult("密码最少 " + setting.getPasswordMinLen() + " 个字符！");
            } else if (setting.getPasswordMaxLen() != null
                    && setting.getPasswordMaxLen() > 0
                    && bo.getPassword().length() > setting.getPasswordMaxLen()) {
                return ResultUtil.failureResult("密码最多 " + setting.getPasswordMaxLen() + " 个字符！");
            }
        } else if (bo.getPassword().length() < 6) {
            return ResultUtil.failureResult("密码最少 6 个字符！");
        }

        bo.setId(Constants.getCurrentUser().getEmployeeId());
        if (employeeService.updatePassword(bo) > 0) {
            UserDetail userDetail = Constants.getCurrentUser();
            userDetail.getEmployee().setPasswordInit(Constants.NO);
            userDetail.getEmployee().setPasswordTime(System.currentTimeMillis());
            Constants.setSessionUser(userDetail);
            return ResultUtil.successResult("密码修改成功！");
        } else {
            return ResultUtil.failureResult("密码修改失败！");
        }
    }

    @PostMapping(value = "/queryUnreadCount")
    public String queryUnreadCount(@RequestBody MessageBO bo) {
        bo.setEmployeeId(Constants.getCurrentUserId());
        return ResultUtil.successResult(messageService.queryUnreadCount(bo));
    }

    @PostMapping("/queryMessagePage")
    public String queryMessagePage(@RequestBody MessageBO bo) {
        bo.setEmployeeId(Constants.getCurrentUserId());
        return ResultUtil.successResult(messageService.queryMessagePage(bo));
    }

    @PostMapping("/updateRead")
    public String updateRead(@RequestBody MessageBO bo) {
        bo.setEmployeeId(Constants.getCurrentUserId());
        return ResultUtil.successResult(messageStatusService.updateRead(bo));
    }

    @PostMapping("/updateTheme")
    public String updateTheme(@RequestBody EmployeeBO bo) {
        UserDetail userDetail = Constants.getCurrentUser();
        userDetail.getEmployee().setTheme(bo.getTheme());
        Constants.setSessionUser(userDetail);

        bo.setId(userDetail.getEmployeeId());
        return ResultUtil.successResult(employeeService.updateTheme(bo));
    }
}
